<template>
  <el-dialog
    :title="titleType"
    width="700px"
    @close="cancel"
    :visible.sync="isShow"
    top='5vh'
    append-to-body
    :close-on-click-modal='false'>
    <div class="system-template-cnotainer">
      <!--S 公司信息 -->
      <!-- 名称、电话、地址、邮箱、自助门户(默认全选) -->
      <el-row>
        <h2>{{$t('task.setting.taskTypeSetting.flow.components.companyInfo')}}</h2>
        <el-checkbox-group v-model="tenantFields">
          <el-checkbox
            v-for="item in companyColumns"
            :key="item.key"
            :label="item.key">
            {{item.label}}
          </el-checkbox>
        </el-checkbox-group>
      </el-row>
      <!--E 公司信息 -->

      <!--S 客户信息 -->
      <!--名称、电话、地址、邮箱、自助门户(默认全选)-->
      <el-row>
        <h2>{{$t('task.setting.taskTypeSetting.flow.components.customerInfo')}}</h2>
        <el-checkbox-group v-model="customerFields">
          <el-checkbox key="name" label="name">{{$t('common.base.customer')}}</el-checkbox>
          <!-- 客户系统字段 -->
          <template v-for="item in customerSysColumns">
            <el-checkbox
              v-if="customerField.setting && customerField.setting.customerOption[item.key]"
              :key="item.key"
              :label="item.key">
              {{item.label}}
            </el-checkbox>
          </template>
        </el-checkbox-group>
      </el-row>
      <!--E 客户信息 -->

      <!--S 工单信息 -->
      <el-row>
        <h2>{{$t('task.taskInfo')}}</h2>
        <el-checkbox-group v-model="taskFields">
          <el-checkbox
            v-for="item in taskColumns"
            :key="item.key"
            :label="item.key">
            {{item.label}}
          </el-checkbox>
        </el-checkbox-group>
      </el-row>
      <!--E 工单信息 -->

      <!--S 工单信息 -->
      <el-row v-for="(custom, index) in customNodeInfo" :key="`${custom.value}_${index}`">
        <h2>{{ custom.groupName }}</h2>
        <el-checkbox-group v-model="customNodeCheck[custom.value]">
          <el-checkbox
              v-for="item in custom.fieldList"
              :key="item.key"
              :label="item.key">
            {{item.label}}
          </el-checkbox>
        </el-checkbox-group>
      </el-row>
      <!--E 工单信息 -->

      <!--S 回执信息 -->
      <el-row>
        <h2>{{$t('task.receiptInfo')}}</h2>
        <el-checkbox-group v-model="receiptFields">
          <el-checkbox
            v-for="item in receiptColumns"
            :key="item.key"
            :label="item.key">
            {{item.label}}
          </el-checkbox>
        </el-checkbox-group>
      </el-row>
      <!--E 回执信息 -->

      <!--S 回执信息：费用合计 -->
      <el-row v-if="isSettlementRule">
        <h2>{{$t('task.receiptInfo')}}：{{$t('task.detail.components.totalFee')}}</h2>
        <el-checkbox-group v-model="settlementFields">
          <el-checkbox
            v-for="item in settlementColumns"
            :key="item.fieldName"
            :label="item.fieldName">
            {{item.displayName}}
          </el-checkbox>
        </el-checkbox-group>
      </el-row>
      <!--E 回执信息：费用合计 -->

      <!--S 工单审核信息 -->
      <el-row>
        <h2>{{$t('task.setting.approveInfo')}}</h2>
        <el-checkbox-group v-model="approverFields">
          <el-checkbox
            v-for="item in taskAuditColumns"
            :key="item.key"
            :label="item.key">
            {{item.label}}
          </el-checkbox>
        </el-checkbox-group>
      </el-row>
      <!--E 工单审核信息 -->

      <!--S 子表单 -->
      <el-row v-for="(sub, idx) in subFormFieldList" :key="`${idx}_${sub.fieldName}`">
        <h2>{{sub.displayName}}</h2>
        <el-checkbox-group v-model="subFormFields[sub.fieldName]">
          <el-checkbox
            v-for="item in sub.subFormFieldList"
            :key="item.fieldName"
            :label="item.fieldName">
            {{item.displayName}}
          </el-checkbox>
        </el-checkbox-group>
      </el-row>

      <el-row v-for="(sub, idx) in subReceiptFields" :key="`${idx}_${sub.fieldName}`">
        <h2>{{$t('task.list.zhongqiText.receiptInfo')}}: {{sub.displayName}}</h2>
        <el-checkbox-group v-model="subFieldNameMapReceiptFields[sub.fieldName]">
          <el-checkbox
            v-for="item in sub.subFormFieldList"
            :key="item.fieldName"
            :label="item.fieldName">
            {{item.displayName}}
          </el-checkbox>
        </el-checkbox-group>
      </el-row>
      <!--E 子表单 -->

      <!--S 附加组件信息 -->
      <el-row v-for="(cardInfo, idx) in cardDetailList" :key="idx">
        <h2>{{$t('task.record.taskCard')}}: {{getCardNameLabel(cardInfo)}}</h2>
        <el-checkbox-group v-model="cardFields[cardInfo.cardId]">
          <el-checkbox
            v-for="item in cardInfo.fields"
            :key="item.fieldName"
            :label="item.fieldName">
            {{item.displayName}}
          </el-checkbox>
          <!-- 附加组件系统字段 -->
          <el-checkbox
            v-for="item in cardSysColumns"
            :key="item.key"
            :label="item.key">
            {{item.label}}
          </el-checkbox>
        </el-checkbox-group>
      </el-row>
      <!--E 附加组件信息 -->

      <!--S 附件信息 --> 
      <el-row>
        <h2>{{$t('task.setting.taskTypeSetting.flow.components.attachmentInfo')}}</h2>
        <!-- 工单附件 -->
        <el-checkbox-group v-model="taskAttachments">
          <el-checkbox
            v-for="item in taskAttachmentColumns"
            :key="item.fieldName"
            :label="item.fieldName">
            {{$t('common.base.task')}}-{{item.displayName}}
          </el-checkbox>
        </el-checkbox-group>
        <!--自定义节点的附件-->
        <el-checkbox-group
            v-for="(custom, index) in customNodeAttachments"
            :key="`${custom.value}_${index}_attachment`"
            v-model="customNodeAttachmentCheck[custom.value]">
          <el-checkbox
              v-for="item in custom.fieldList"
              :key="item.fieldName"
              :label="item.fieldName">
            {{custom.groupName}}-{{item.displayName}}
          </el-checkbox>
        </el-checkbox-group>

        <!-- 回执附件-->
        <el-checkbox-group v-model="receiptAttachments">
          <el-checkbox
            v-for="item in receiptAttachmentColumns"
            :key="item.fieldName"
            :label="item.fieldName">
            {{ item.fieldName === 'receiptAttachment' ? $t('task.setting.taskTypeSetting.flow.components.systemTemplateTitle1') : $t('task.setting.taskTypeSetting.flow.components.systemTemplateTitle2', {name: item.displayName}) }}
          </el-checkbox>
        </el-checkbox-group>
        <!-- 单次附件组件附件 -->
        <el-checkbox-group v-model="singleCardInfoAttachments">
          <el-checkbox
            v-for="item in singleCardInfoAttachmentColumns"
            :key="item.fieldName"
            :label="item.fieldName">
            {{`${getCardNameLabel(item)}-${item.displayName}` }}
          </el-checkbox>
        </el-checkbox-group>
        <!-- 多次附件组件附件 -->
        <el-checkbox-group v-model="multipleCardInfoAttachments">
          <el-checkbox
            v-for="item in multipleCardInfoAttachmentColumns"
            :key="item.fieldName"
            :label="item.fieldName">
            {{`${getCardNameLabel(item)}-${item.displayName}` }}
          </el-checkbox>
        </el-checkbox-group>
      </el-row>
      <!--E 附件信息 -->
      <!--S 客户满意度 -->
       <el-row>
        <h2>{{$t('common.customer.questionnaire.customerSatisfaction')}}</h2>
        <el-checkbox-group v-model="satisfactionFields">
          <el-checkbox
            v-for="item in satisfactionFieldsList"
            :key="item.key"
            :label="item.key">
            {{item.label}}
          </el-checkbox>
        </el-checkbox-group>
      </el-row>
      <!--E 客户满意度 -->
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="saveSystemTemplate" :loading="pending">{{$t('common.base.save')}}</el-button>
    </div>
  </el-dialog>
</template>

<script>
import _ from 'lodash';
// columns 
import { companyColumns, customerSysColumns, taskColumns, receiptColumns, cardSysColumns, faultLibraryColumns, taskCreateAuditColumns, taskAuditColumns } from './columns';
// api
import * as TaskApi from '@src/api/TaskApi.ts';
import * as settingApi from '@src/api/SettingApi';
import i18n from '@src/locales'
import { smoothLogisticsField } from '@service/LogisticsService'
import { FieldTypeMappingEnum, LogisticsFieldNameMappingEnum } from '@model/enum/FieldMappingEnum'
import { CardNameLabelEnum } from '@model/enum/LabelEnum'
import { getRootWindow } from '@src/util/dom'
/* enum*/
import { GrayFunctionEnum } from 'pub-bbx-global/pageType/dist/grayFunction'


export default {
  name: 'system-template-dialog',
  props: {
    visiable: {
      type: Boolean,
      default: false
    },
    type: {
      type: String,
      default: ''
    },
    taskTypeId: {
      type: String,
      default: ''
    },
    reportSetting: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      isShow: false,
      pending: false,

      taskTypeConfig: {}, // 当前工单类型配置详情(除了附加组件)
      cardDetailList: [], // 附加组件列表

      taskFieldList: [], // 工单表单字段
      receiptFieldList: [], // 回执表单字段
      subFormFieldList: [], // 子表单字段
      satisfactionFieldsList: [], //满意度字段

      // 勾选项
      approverFields: [], // 工单审核字段
      tenantFields: [], // 公司字段
      customerFields: [], // 客户字段
      taskFields: [], // 工单字段
      receiptFields: [], // 回执字段
      subFormFields: {}, // 子表单字段
      subFieldNameMapReceiptFields: {},
      subReceiptFields: [], // 回执子表单
      cardFields: {}, // 组件字段
      satisfactionFields: [], //客户满意度字段

      taskAttachments: [], // 工单附件字段
      receiptAttachments: [], // 回执附件字段
      singleCardInfoAttachments: [], // 单次附加组件附件字段
      multipleCardInfoAttachments: [], // 多次附加组件附件字段
      customNodeAttachments: [], // 当前工单类型自定义节点的附件字段
      
      signatureSetting: false, // 审批签名配置

      settlementFields: [], // 回执信息费用合计字段
      settlementColumns: [], // 回执信息费用的展示字段

      customNodeInfo: [], // 当前工单类型自定义节点信息和字段
      customNodeCheck: {}, // 当前工单类型自定义节点勾选的字段
      customNodeAttachmentCheck: {}, // 当前工单类型自定义节点勾选的附件值

    }
  },
  computed: {
    // 结算规则灰度
    isSettlementRule() {
      const RootWindow = getRootWindow(window)
      return RootWindow.grayAuth?.settlementRule || false
    }, 
    titleType() {
      return this.type === 'reportSetting' ? i18n.t('task.setting.taskTypeSetting.flow.components.systemTemplateTitle3') : i18n.t('task.setting.taskTypeSetting.flow.components.systemTemplateTitle4');
    },
    customerField() { // 工单表单过滤出来的客户控件字段
      return this.taskFieldList.find(item => item.formType == 'customer' && item.fieldName == 'customer') || {};
    },
    // 是否开启工单草稿灰度
    isTaskCreateHalfGray() {
      const RootWindow = getRootWindow(window)
      return RootWindow?.grayAuth?.taskCreateHalf
    },
    enableSignature() {
      return this.signatureSetting;
    },
    taskAuditColumns() {
      let taskAuditColumnsData = taskAuditColumns;
      // if(!this.enableSignature) { // 暂时不加权限控制了
      //   taskAuditColumnsData = taskAuditColumnsData.filter(item => item.mode !== 'sign');
      // }
      if(this.isTaskCreateHalfGray) return [...taskCreateAuditColumns, ...taskAuditColumnsData];
      return taskAuditColumnsData;
    },
    companyColumns() {
      return companyColumns;
    },
    customerSysColumns() {
      return customerSysColumns;
    },
    // 故障库字段
    hasFaultLibrary() {
      return this.taskFieldList.findIndex(item => item.fieldName === 'faultLibrary') > -1
    },
    isFaultLibraryColumns() {
      return this.hasFaultLibrary ? faultLibraryColumns : []
    },
    taskColumns() {
      return [
        ...this.taskFieldList.filter(item => {
          // 服务报告和打印都需要过滤连接器
          const filterFormType = ['attachment', 'customer', 'separator', 'info', 'faultLibrary', FieldTypeMappingEnum.JsCodeBlock, 'connector']
          return !(filterFormType.includes(item.formType)) && item.enabled && !item?.setting?.isSubForm;
        }),
        ...taskColumns,
        ...this.isFaultLibraryColumns
      ];
    },
    receiptColumns() {
      return [
        ...receiptColumns,
        ...this.receiptFieldList.filter(item => {
          const filterFormType = ['attachment', 'receiptAttachment', 'sparepart', 'serviceIterm', 'systemAutograph', 'separator', 'info', 'relationForm', FieldTypeMappingEnum.JsCodeBlock, 'connector']
          return !(filterFormType.includes(item.formType));
        })
      ];
    },
    cardSysColumns() {
      return cardSysColumns;
    },
    taskAttachmentColumns() {
      return this.taskFieldList
        .filter(item => item.formType === 'attachment')
        .map(({displayName, fieldName}) => {
          return {
            displayName,
            fieldName
          }
        });
    },
    receiptAttachmentColumns() {
      let receiptAttachmentColumns = this.receiptFieldList
        .filter(item => item.formType === 'attachment')
        .map(({displayName, fieldName}) => {
          return {
            displayName,
            fieldName
          }
        });

      if(this.showAttachment) {
        receiptAttachmentColumns.unshift(
          {
            displayName: i18n.t('common.form.type.receiptAttachment'),
            fieldName: 'receiptAttachment'
          }
        )
      }

      return receiptAttachmentColumns;
    },
    showAttachment() {
      return this.taskTypeConfig.options && !!this.taskTypeConfig.options.showAttachment;
    },
    cardAttachmentColumns() {
      let cardAttachmentColumns = [];

      this.cardDetailList.forEach(cardInfo => {
        cardInfo.fields.forEach(field => {
          if(field.formType === 'attachment') {
            cardAttachmentColumns.push({
              cardId: cardInfo.cardId,
              cardName: cardInfo.cardName,
              displayName: field.displayName,
              fieldName: field.fieldName,
              inputType: cardInfo.inputType
            })
          }
        });
      });

      return cardAttachmentColumns;
    },
    singleCardInfoAttachmentColumns() {
      return this.cardAttachmentColumns.filter(item => item.inputType === 'single'); },
    multipleCardInfoAttachmentColumns() {
      return this.cardAttachmentColumns.filter(item => item.inputType === 'multiple');
    },
    // 工单节点拓展灰度
    taskFlowExtend() {
      const RootWindow = getRootWindow(window);
      return RootWindow?.grayAuth?.[GrayFunctionEnum.TaskFlowExtend] ?? false // 工单流程节点灰度
    },
  },
  watch: {
    visiable(val){
      this.isShow = val;
      if(val) {
        this.fetchTaskCardDetailList().then(async () => {
          // 控制接口调用顺序
          await this.getFields('task');
          await this.fetchTasktype();
        })
        this.getFields('task_receipt');
        this.getSatisfactionFields();
        this.getExtendField(); // 结算规则服务报告导出字段
        // this.getSignatureSetting();
      }

    }
  },
  methods:{
    // 获取审批签名配置
    getSignatureSetting() {
      settingApi.getTenantConfigByCodeList({ codeList: ['TASK_APPROVED_SIGN_CONFIG'] }).then((res) => {
        if (res.success) {
          if(!res.success) return this.$message.error(res.message)
          this.signatureSetting = !!res.data.find(item=> item.configCode === 'TASK_APPROVED_SIGN_CONFIG')?.open;
        }
      })
    },
    getExtendField() {
      TaskApi.getExtendField({taskTypeId: this.taskTypeId}).then((res) => {
        if (res.success) {
          this.settlementColumns = res.result.taskSettlement || []
        }
      })
    },
    // 获取附加组件名称的多语言label
    getCardNameLabel(item) {
      const { cardName, cardNameLanguage } = item
      const locale = this.$i18n.locale
      return cardNameLanguage?.locale || CardNameLabelEnum[cardName] || cardName
    },
    cancel() {
      // 关闭弹窗reset
      this.approverFields= []
      this.tenantFields= []
      this.customerFields= []
      this.taskFields= []
      this.receiptFields= []
      this.satisfactionFields= []
      this.cardFields= {}
      this.subFormFields = {}
      this.subFieldNameMapReceiptFields = {}
      this.customNodeCheck = {}
      this.customNodeAttachmentCheck = {}
      this.$emit('update:visiable', false);
    },
    /**
     * 将对象数组转化成字符串数组
     * 注: 因element-ui checkbox组件不支持对象数组, 故需要这样处理
     */
    convertArrayObjectToKey(arr, objKey) {
      if(!Array.isArray(arr)) {
        return [];
      }
      return arr.map(item => item[objKey]);
    },
    /**
     * 将字符串数组转化成对象数组
     */
    convertArrayKeyToObject(arr, objKey, options) {
      if(!Array.isArray(arr)) {
        return [];
      }
            
      return options.filter(item => arr.includes(item[objKey]));
    },
    /**
     * 获取工单设置的除组件外的其他信息
     */
    async fetchTasktype() {
      try {
        let params = {
          id: this.taskTypeId
        };
        let res = await TaskApi.getTaskType(params);

        let reportSetting = _.cloneDeep(this.reportSetting)
        if(reportSetting.templates) delete reportSetting.templates // 清掉个人模版数据templates
        res.data.reportSetting = reportSetting


        // 开启工单节点灰度再获取自定义节点字段
        if(this.taskFlowExtend) {
          this.getTaskNewNodeFieldList(res.data?.[this.type] ?? {});
        }

        if(JSON.stringify(reportSetting) == '{}') { // 服务报告重构 组件直接使用传入的reportSetting
          res.data.reportSetting = {'tenantFields':['name', 'phone', 'email', 'address', 'portal'], 'customerFields':['name', 'product', 'address', 'linkman'], 'taskFields':['taskNo', 'planTime', 'executor'], 'receiptFields':['sparepart', 'service', 'autograph'], 'attachmentFields':{}}
        }

        if(JSON.stringify(res.data.printSetting) == '{}') {
          res.data.printSetting = {'tenantFields':['name', 'phone', 'email', 'address', 'portal'], 'customerFields':['name', 'product', 'address', 'linkman'], 'taskFields':['taskNo', 'planTime', 'executor'], 'receiptFields':['sparepart', 'service', 'autograph'], 'attachmentFields':{}}
        }


        console.log(res.data[this.type], 'res.data[this.type]')




        this.taskTypeConfig = res.data;
        let { approverFields, tenantFields, customerFields, taskFields, receiptFields, settlementFields, satisfactionFields, subFieldNameMap, subFieldNameMapReceipt, cardFields, attachmentFields} = res.data[this.type];
        cardFields = cardFields || [];
        attachmentFields = attachmentFields || [];

        // 获取表单设计器那边客户控件相关的配置
        const customerOption = this.customerField?.setting?.customerOption ?? {}
        if(Object.keys(customerOption).length){
          // 根据表单设计的配置,进行客户相关数据的过滤
          customerFields = customerFields.filter(item => item === 'name' || customerOption[item] );
        }
        this.approverFields = approverFields || [];
        this.tenantFields = tenantFields || [];
        this.customerFields = customerFields || [];
        this.taskFields = taskFields || [];
        this.receiptFields = receiptFields || [];
        this.satisfactionFields = satisfactionFields || [];

        // 数据回显
        this.settlementFields = settlementFields || [];
        this.subFormFields = Object.values(subFieldNameMap).length > 0 ? subFieldNameMap : this.subFormFields

        this.subFieldNameMapReceiptFields = Object.values(subFieldNameMapReceipt).length > 0 ? subFieldNameMapReceipt : this.subFieldNameMapReceiptFields

        
        cardFields.forEach(item => {
          this.cardFields[item.cardId] = item.fields;
        })

        this.taskAttachments = this.convertArrayObjectToKey(attachmentFields.taskAttachments, 'fieldName');
        this.receiptAttachments = this.convertArrayObjectToKey(attachmentFields.receiptAttachments, 'fieldName');
        this.singleCardInfoAttachments = this.convertArrayObjectToKey(attachmentFields.singleCardInfoAttachments, 'fieldName');
        this.multipleCardInfoAttachments = this.convertArrayObjectToKey(attachmentFields.multipleCardInfoAttachments, 'fieldName');
      } catch (err) {
        console.error('fetch Tasktype => err', err);
      }
    },
    /**
     * 获取工单表单/回执表单字段
     */
    async getFields(tableName) {
      try {
        let params = {
          typeId: this.taskTypeId,
          tableName
        };
        let res = await TaskApi.getFields(params);

        res.map(item => {
          item.label = item.displayName;
          item.key = item.fieldName;
          return item;
        });

        if(tableName === 'task') {
          // 拆分物流组件字段
          this.taskFieldList = smoothLogisticsField(res || []);
          this.taskFieldList.forEach((item) => {
            if(item.formType === 'logistics'){
              if(item.fieldName.indexOf(LogisticsFieldNameMappingEnum.LogisticsNo) > -1){
                item.label = i18n.t('common.base.logisticsNo')
                item.key = item.field
              }
          
              if(item.fieldName.indexOf(LogisticsFieldNameMappingEnum.LogisticsCompany) > -1){
                item.label = i18n.t('common.base.logisticsCompany')
                item.key = item.field
              }
            }
          })
          this.subFormFieldList = res.filter(item => item?.setting?.isSubForm)
          this.subFormFieldList.forEach(item => {
            this.$set(this.subFormFields, item.fieldName, [])
          })
        }


        console.log(this.subFormFields, 'this.subFormFields接口返回的')

        if(tableName === 'task_receipt'){
          this.receiptFieldList = smoothLogisticsField(res || []);
          this.receiptFieldList.forEach((item) => {
            if(item.formType === 'logistics'){
              if(item.fieldName.indexOf(LogisticsFieldNameMappingEnum.LogisticsNo) > -1){
                item.label = i18n.t('common.base.logisticsNo')
                item.key = item.field
              }
          
              if(item.fieldName.indexOf(LogisticsFieldNameMappingEnum.LogisticsCompany) > -1){
                item.label = i18n.t('common.base.logisticsCompany')
                item.key = item.field
              }
            }
          })
          this.subReceiptFields = this.receiptFieldList.filter(item => item?.setting?.isSubForm)

          this.subReceiptFields.forEach(item => {
              this.$set(this.subFieldNameMapReceiptFields, item.fieldName, [])
          })

        console.log(this.subFieldNameMapReceiptFields, 'this.subFieldNameMapReceiptFields接口')

        }
      } catch (err) {
        console.error('fetch TaskTypeFields => err', err);
      }
    },

    /*根据工单类型id获取自定义节点和对应的表单字段*/
    async getTaskNewNodeFieldList(customNodeFormValue) {
      try {
        // 先置空
        this.customNodeCheck = {}
        this.customNodeAttachmentCheck = {}
        this.customNodeAttachments = [];

        const params = {
          taskTypeId: this.taskTypeId,
        };
        const { success, result = [] } = await TaskApi.getTaskNodeFieldListByTypeIds(params);

        if(!success) return

        this.customNodeInfo = result?.filter(item => item.fieldList?.length)?.map(item => {
          // 回显节点字段之前勾选的值
          this.$set(this.customNodeCheck, item.nodeBizId, customNodeFormValue?.[item.nodeBizId] ?? [])
          // 回显附件的值
          const customAttachmentValues = this.convertArrayObjectToKey(customNodeFormValue?.attachmentFields?.[item.nodeBizId] ?? [], 'fieldName');
          this.$set(this.customNodeAttachmentCheck, item.nodeBizId, customAttachmentValues)

          // 处理附件的字段
          const attachmentFields = item?.fieldList?.filter(item => item.formType === 'attachment')?.map(item => {
            return {
              fieldName: item.fieldName,
              displayName: item.displayName
            }
          }) ?? []
          attachmentFields?.length && this.customNodeAttachments.push({
            groupName: item.nodeName,
            fieldList: attachmentFields,
            value: item.nodeBizId,
          })

          const filterField = ['separator', 'info', 'relationTask', 'attachment', 'connector']
          const fieldList = (item.fieldList || [])?.filter(f => !filterField.includes(f.formType)).map(field => ({
            label: field.displayName,
            key: field.fieldName,
          }));
          return {
            groupName: `${this.$t('task.taskNodeUserListInfo', { data: item.nodeName })}`,
            fieldList,
            value: item.nodeBizId,
          }
        })?.filter(item => item.fieldList?.length) ?? [] // 再过滤下
      } catch (e) {
        console.error(e)
      }
    },
    async getSatisfactionFields(tableName) {
      try {
        let params = {
          templateId: this.taskTypeId
        };
        let {result} = await TaskApi.getSatisfactionFields(params);

        result.map(item => {
          item.label = item.displayName;
          item.key = item.fieldName;
          return item;
        });

        this.satisfactionFieldsList = result;
      } catch (err) {
        console.error('fetch satisfaction => err', err);
      }
    },
    /**
     * 获取附加组件列表
     */
    async fetchTaskCardDetailList() {
      try {
        let res = await TaskApi.getTaskCardDetailList({typeId: this.taskTypeId});

        this.cardDetailList = res || [];
        // 附加组件是关联工单并且开启展示系统字段处理
        this.cardDetailList.forEach(cardInfo=> {
          const targetIndex = cardInfo.fields.findIndex(f => f.formType == 'related_task' && f?.setting?.isShowSystemFields);
          if (targetIndex !== -1) {
            const targetDataArray = cardInfo.fields[targetIndex].subCardFieldList || [];
            cardInfo.fields.splice(targetIndex + 1, 0, ...targetDataArray);
          }
          cardInfo.fields =  cardInfo.fields.filter(item=> item.formType !== FieldTypeMappingEnum.JsCodeBlock)
        })

        // 服务报告过滤连接器附加组件(TODO: 连接器不用翻译)
        if (this.type == 'reportSetting') {
          this.cardDetailList = this.cardDetailList.filter(item => item.specialfrom != '连接器' )
        }

        // 备件清单附加组件添加字段合计金额（specialfrom去判断是否是备件清单，工单详情也是这么判断的，中文判断）
        this.cardDetailList = this.cardDetailList?.map(item => {
          if(item.specialfrom === '备件清单') {
            item.fields.push({
              displayName: this.$t('task.detail.components.totalExpense'),
              fieldName: 'sparePartInventory_amountTotal',
            })
          }
          return item
        })

        res.map(item => {
          this.$set(this.cardFields, item.cardId, []);
        })
      } catch (err) {
        console.error('fetch TaskCardDetailList => err', err);
      }
    },
    /**
     * 保存
     */
    async saveSystemTemplate() {
      let cardFields = Object.keys(this.cardFields).map(cardId => {
        return {
          cardId,
          fields: this.cardFields[cardId]
        }
      });

      // 处理自定义节点的附加组件
      let customNodeAtts = {}
      for(const key in this.customNodeAttachmentCheck) {
        const value = this.customNodeAttachmentCheck[key]
        const fields = this.customNodeAttachments?.find(item => item.value === key)?.fieldList ?? []
        this.$set(customNodeAtts, key, this.convertArrayKeyToObject(value, 'fieldName', fields))
      }
      let attachmentFields = {
        taskAttachments: this.convertArrayKeyToObject(this.taskAttachments, 'fieldName', this.taskAttachmentColumns),
        receiptAttachments: this.convertArrayKeyToObject(this.receiptAttachments, 'fieldName', this.receiptAttachmentColumns),
        singleCardInfoAttachments: this.convertArrayKeyToObject(this.singleCardInfoAttachments, 'fieldName', this.singleCardInfoAttachmentColumns),
        multipleCardInfoAttachments: this.convertArrayKeyToObject(this.multipleCardInfoAttachments, 'fieldName', this.multipleCardInfoAttachmentColumns),
        ...customNodeAtts,
      }

      // 排序
      let taskFields=[]

      this.taskColumns.forEach(item=>{
        if(item.key && this.taskFields.includes(item.key)){
          taskFields.push(item.key)
        }
      })

      // 故障库字段
      let faultLibraryFields = []
      this.isFaultLibraryColumns.forEach(item => {
        if(item.key && this.taskFields.includes(item.key)){
          faultLibraryFields.push(item.key)
        }
      })
      
      
      let params = {
        id: this.taskTypeId,
        [this.type]: {
          approverFields: this.approverFields,
          tenantFields: this.tenantFields,
          customerFields: this.customerFields,
          taskFields: taskFields,
          receiptFields: this.receiptFields,
          satisfactionFields: this.satisfactionFields,
          cardFields,
          attachmentFields,
          faultLibraryFields,
          subFieldNameMap: this.subFormFields, // 服务商子表单
          settlementFields: this.settlementFields, // 费用合计字段
          subFieldNameMapReceipt: this.subFieldNameMapReceiptFields
        }
      }

      // 拼接自定义节点选择的字段
      params[this.type] = {
        ...params[this.type],
        ...this.customNodeCheck,
      }
      this.pending = true;

      try {
        // 如果是服务报告只需要传出setting即可
        if(this.type === 'reportSetting') {
          this.$emit('reportSettingSave', params.reportSetting)
        } else {
          let res = await TaskApi.saveSystemPrint(params);
          if(res.succ) {
            this.$platform.notification({
              type: 'success',
              title: i18n.t('common.base.saveSuccess')
            });
          } else {
            this.$platform.notification({
              type: 'error',
              title: res.message
            });
          }
        }

        this.cancel();
      } catch (err) {
        console.error('saveSystemTemplate => err', err);
      } finally{
        this.pending = false;
      }
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-dialog {
  height: 90vh;
}
::v-deep .el-dialog__body {
  height: calc(100% - 108px);
  overflow: auto;
}
.system-template-cnotainer {
    & > div {
        font-size: 14px;
        margin-bottom: 24px;
        ::v-deep .el-checkbox {
          margin-right: 32px;
          color: #595959;
        }
        h2{
            font-size: 16px;
            margin-bottom: 8px;
        }
    }
}
</style>